import Dayjs from 'dayjs';
import { Notify } from 'vant';
import Store from '@/stores';
import Router from '@/router';
import { i18n } from '@/locales';

const plusReady = callback => {
  if (window.plus) {
    setTimeout(function () {
      callback();
    }, 0);
  } else {
    document.addEventListener(
      'plusready',
      function () {
        callback();
      },
      false,
    );
  }
};

const checkPlus = callBack => {
  if (window.plus) {
    callBack();
  } else {
    Notify('此功能需要真机调试');
  }
};

const handleExit = () => {
  Store.commit('common/initData');
  Store.commit('common/setCache', []);
  Router.replace({
    path: '/login',
  });
};

const guid = () => {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
};

const noToken = async () => {
  Notify.alert({
    title: i18n.global.t('hint'),
    message: i18n.global.t('noToken'),
  }).then(() => {
    handleExit();
  });
};

const formatDate = (date, rule = 'YYYY-MM-DD HH:mm:ss') => {
  let result = '';
  if (date && !date.toString().startsWith('0001')) {
    result = Dayjs(date).format(rule);
  }
  return result;
};

export default {
  guid,
  noToken,
  checkPlus,
  plusReady,
  handleExit,
  formatDate,
};
